using ChatGpt_WebApp.ApiDto;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace ChatGpt_WebApp.Fillter;

public class GlobalExceptionFilter : IExceptionFilter
{
    readonly IHostEnvironment _env;
    readonly ILogger<GlobalExceptionFilter> _logger;

    public GlobalExceptionFilter(IHostEnvironment env, ILogger<GlobalExceptionFilter> logger)
    {
        _env = env;
        this._logger = logger;
    }

    public void OnException(ExceptionContext context)
    {
        //通过HTTP请求头来判断是否为Ajax请求，Ajax请求的request headers里都会有一个key为x-requested-with，值“XMLHttpRequest”
        var requestData = context.HttpContext.Request.Headers.ContainsKey("x-requested-with");
        bool IsAjax = false;
        if (requestData)
        {
            IsAjax = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest" ? true : false;
        }

        if (!context.ExceptionHandled)
        {
            string message = context.Exception.Message;
            if (context.Exception is BusinessException)
            {
                var ex = context.Exception as BusinessException;
                context.Result = new JsonResult(new ApiResult()
                {
                    Code = 0,
                    Message = ex.Message,
                    Data = null,
                    Success = false
                });
            }
            else
            {
                var ex = context.Exception;
                _logger.LogError(ex, "系统异常:" + ex.Message);
                context.Result = new JsonResult(new ApiResult()
                {
                    Code = 500,
                    Message = "系统异常:" + ex.Message,
                    Data = null,
                    Success = false
                });
            }

            context.ExceptionHandled = true;
        }
    }

}
